import React, { useState, useEffect, useMemo } from 'react'
import { Table, Card, Select, Tag, Alert, Button, Space, Image, Popconfirm, message } from 'antd'
import $http from '@/services/http.service.v2';
import $helper from '@/services/helper.service';
import $wss from "@/services/wss.service"
import RoleScreenshotDialog from "./parts/RoleScreenshotDialog"
import moment from 'moment';
import environment from "@/environment"
window.moment = moment

export default function PetAnalyzePage() {
  const [data, setData] = useState({dateList: [], dataSource: []})
  const [selectDate, setSelectDate] = useState("")
  useEffect(() => {
    $http.getCraftLog().subscribe(
      res => {
        const list = res.data.map(parseLine).filter(_ => _ !== undefined)
        const dateList = [...new Set(list.map(item => item.date))].reverse()
        setData({dataSource: list, dateList})
        setSelectDate([...dateList].shift())
      }
    )
  }, [])

  function onShowCourse() {

  }

  function onHandleAutoXnTask() {
    const users = tableDataSource.filter(e => +e.awardQuestState === 4).map(e => e.role).filter(e => e)
    // const users = tableDataSource.filter(e => e.awardQuestState.startsWith("3_")).map(e => e.role).filter(e => e)
    $wss.startCraftGroup({
      auto_run_record_events: 1,
      record_events_file: environment.missionXnQuestJsonFile.completeJson,
      loop_roles: users,
      start_idx: 0,
      limit: 0,
    })
    // console.error(users)
    // record.awardQuestState
  }

  function onHandleAuto_HLT_FACT_Quest() {
    const users = tableDataSource.filter(e => e.factionState.indexOf("name_荒猎团#hasRewardPending_1") >= 0).map(e => e.role).filter(e => e)
    // console.error("users", users)
    $wss.startCraftGroup({
      auto_run_record_events: 1,
      record_events_file: environment.missionXnQuestJsonFile.competeHLT_FACT_QuestJson,
      loop_roles: users,
      start_idx: 0,
      reset_keyboard: 1,
      limit: 0,
    })
  }

  function formatPetMissionText(text) {
    return (text || "").split("|").filter(e => e).map(e => {
      let obh = {}
      e.split("#").forEach(item => {
        const [k, v] = item.split("_")
        obh[k] = v
      })
      return obh
    })
  }

  function formatRoleLineData(_roleLines) {
    const roleLines = [..._roleLines].map(e => {
      return {...e, itemID_Pet_7_formatted: formatPetMissionText(e.itemID_Pet_7)}
    })
    roleLines.sort((a, b) => moment(a.time) - moment(b.time))
    let petMissions = roleLines.reduce((acc, val) => {
      let missions = formatPetMissionText(val.itemID_Pet_7)
      return acc.concat(missions)
    }, [])
    let uniquePetMissions = (function(missions) {
      let mids = [...new Set(missions.map(e => e.ID))]
      return mids.map(e => missions.find(item => item.ID === e))
    })(petMissions)
    return {
      counts: roleLines.length,
      petCharmCount: Math.max(...roleLines.map(e => +e.itemID_Pet_3)),
      lastDayPetCharmCount: Math.max(...roleLines.map(e => +e.itemID_Pet_3)),
      followersCount: Math.max(...roleLines.map(e => +e.itemID_Pet_6)),
      renownLevel: Math.max(...roleLines.map(e => +e.itemID_Pet_5)),
      missionLevel: Math.max(...roleLines.map(e => +e.itemID_Pet_4)),
      userAnimaQuantity: +[...roleLines].pop()?.itemID_Pet_1,
      bagAnimaQuantity: +[...roleLines].pop()?.itemID_Pet_2,
      petMissions,
      uniquePetMissions,
      roleLines,
      lastRunTime: [...roleLines].pop()?.time,
      awardQuestState: [...roleLines].pop()?.itemID_Pet_8,
      factionState: [...roleLines].pop()?.itemID_Pet_9,
      speedState: [...roleLines].pop()?.itemID_Pet_11,
      jrzmCount: [...roleLines].pop()?.itemID_Pet_12 || 0,
      userConcentration: [...roleLines].pop()?.itemID_Pet_13 || null,
    }
  }

  const tableDataSource = useMemo(() => {
    if (!selectDate) return []
    let list = data.dataSource.filter(item => item.date === selectDate)
    let lastDayList = data.dataSource.filter(item => item.date === moment(selectDate).subtract(1, 'day').format('YYYY-MM-DD'))
    const roles = [...new Set(list.map(e => e.role))]
    return roles.map(role => {
      const roleLines = list.filter(e => e.role === role)
      // if (role === "兽丶兽") console.error("wtf", roleLines)
      const lastDayRoleLines = lastDayList.filter(e => e.role === role)
      return {
        role,
        ...formatRoleLineData(roleLines),
        lastDay: formatRoleLineData(lastDayRoleLines)
      }
    })
  }, [data, selectDate])
  const subStat = useMemo(() => {
    if (tableDataSource.length <= 0) return ""
    let totalPetCharmCount = tableDataSource.reduce((acc, val) => acc + val.petCharmCount, 0)
    let lastDayPetCharmCount = tableDataSource.reduce((acc, val) => acc + val.lastDay.petCharmCount, 0)
    let totalPetTaskCount = tableDataSource.reduce((acc, val) => acc + val.uniquePetMissions.length, 0)
    let recentTaskTime = tableDataSource?.[0]?.lastRunTime || "未知"
    console.error("tableDataSource", tableDataSource)
    const petResult = `宠物币总数: ${totalPetCharmCount}(+${totalPetCharmCount - lastDayPetCharmCount}),刷新任务数: ${totalPetTaskCount},最近任务时间: ${recentTaskTime}`
    const xnQuestResult = `心能任务: [交任务：${tableDataSource.filter(e => e.awardQuestState === "4").length}]..[完成中：${tableDataSource.filter(e => (`${e.awardQuestState}`).startsWith("3")).length}]`
    // "name_不朽军团#hasRewardPending_0|name_荒猎团#hasRewardPending_0|name_晋升者#hasRewardPending_0|name_收割者之庭#hasRewardPending_0"
    const factResult = `声望：[荒猎团： ${tableDataSource.reduce((acc, val) => {
      return acc + (val.factionState.indexOf("name_荒猎团#hasRewardPending_1") >= 0 ? 1 : 0)
    }, 0)}]..[其他：${tableDataSource.reduce((acc, val) => {
      return acc + 
        (val.factionState.indexOf("name_不朽军团#hasRewardPending_1") >= 0 ? 1 : 0) + 
        (val.factionState.indexOf("name_晋升者#hasRewardPending_1") >= 0 ? 1 : 0) + 
        (val.factionState.indexOf("name_收割者之庭#hasRewardPending_1") >= 0 ? 1 : 0)
    },0)}]`
    return `${petResult}<br/>${xnQuestResult}<br/>${factResult}`
  }, [tableDataSource])

  function onDateChange(date) {
    setSelectDate(date)
  }

  function formatSpeedState(state) {
    const speed = (state || "").split("|")
    if (speed.length < 2) return (<><Tag>未知</Tag></>)
    let speed1 = (+speed[0]).toFixed(2)
    return (<><Tag color={`${speed1 > 7.35 ? "red" : ""}`}>{speed1}</Tag></>)
  }

  const formatAwardStateMap = _state => {
    let state = _state
    let cond = ""
    if ((_state || "").startsWith("3_")) {
      state = 3
      cond = _state.replace("3_", "").replace("心能资源", "").trim()
    }
    let mapSet = {
      0: {text: "未知", color: "gold"},
      1: {text: "已交接", color: "green"},
      2: {text: "接任务", color: "geekblue"},
      3: {text: cond ? `完成中[${cond}]` : "完成中", color: "#44b549"},
      4: {text: "交任务", color: "red"},
    }
    return <Tag color={mapSet[+state || 0].color}>{mapSet[+state || 0].text}</Tag>
  }
  function formatFacState(state) {
    // "name_不朽军团#hasRewardPending_0|name_荒猎团#hasRewardPending_0|name_晋升者#hasRewardPending_0|name_收割者之庭#hasRewardPending_0"
    let list = [];
    (state || "").split("|").forEach(e => {
      let obj = {}
      e.split("#").forEach(d => {
        let [k ,v] = d.split("_")
        obj[k] = v
      })
      list.push(obj)
    });
    return list.filter(e => e.hasRewardPending === "1").map((e,idx) => {
      return <Tag color="red" key={idx}>{e.name}</Tag>
    })
  }
  const columns = [
    {
      title: '序号',
      dataIndex: 'role',
      render: (_, _record, index) => {
        return <a>{index + 1}</a>
      },
    },
    {
      title: '角色',
      dataIndex: 'role',
      render: (_, record) => {
        const url = `https://wonew-wss.frp.wonew.top/screenshot/${selectDate}/${_}.webp`
        return (
          <>
            {_}[<span className={(record.jrzmCount || 0) < 10 ? 'bg-red-600' : ''}>匠人{record.jrzmCount || 0}</span>]{record.userConcentration ? `[${record.userConcentration}]` : ''}
            <Image 
              width={50} 
              preview={{src: `${url}?v=${Date.now()}`}}
              src={url}
              fallback=""
            />
          </>
        )
      }
    },
    {
      title: '心能任务',
      dataIndex: 'role',
      render: (_, record) => {
        return (
          <p>{formatAwardStateMap(record.awardQuestState)}</p>
        )
      }
    },
    {
      title: '速度',
      dataIndex: 'role',
      render: (_, record) => {
        return (
          <p>{formatSpeedState(record.speedState)}</p>
        )
      }
    },
    {
      title: '声望',
      dataIndex: 'role',
      render: (_, record) => {
        return (
          <p>{formatFacState(record.factionState)}</p>
        )
      }
    },
    {title: "宠物币", dataIndex: "petCharmCount", render: (_, record) => {
      return <p>{`${record.petCharmCount}(+${record.petCharmCount - record.lastDay.petCharmCount})${record.uniquePetMissions.length > 0 ? `[+${record.uniquePetMissions.length}]` : ""}`}</p>
    } },
    // {title: "战役", dataIndex: "missionLevel" },
    // {title: "盟约", dataIndex: "renownLevel", render: (_, record) => record.renownLevel + 1},
    // {title: "追随者", dataIndex: "followersCount"},
    // {"title": "专注", dataIndex: "userConcentration"},
    {
      title: "心能",
      children: [
        {title: "总计", dataIndex: "bagAnimaQuantity", render: (_, record) => {
          let total = record.bagAnimaQuantity + record.userAnimaQuantity
          let lastDayTotal = record.lastDay.bagAnimaQuantity + record.lastDay.userAnimaQuantity
          return <span className={total < 1000 ? "text-red-500" : ""}>{total}({total-lastDayTotal})</span>
        } },
        {title: "圣所", dataIndex: "userAnimaQuantity", render: (_, record) => <span className={record.userAnimaQuantity < 500 ? "text-red-500" : "text-green-500"}>{record.userAnimaQuantity}</span> },
        {title: "背包", dataIndex: "bagAnimaQuantity" },
      ]
    }
  ];

  function parseLine(line) {
    const types = ["MISSION_PET_STATE"]
    if (types.every(type => !line.includes(type))){
      return undefined
    }
    
    const lineTime = line.match(/\[.*?\]/g)[0].replace("]", "").replace("[", "")
    const lineContent = line.match(/\{.*?\}/g)[0].replace("{", "").replace("}", "")
    let lineObject = {}
    new URLSearchParams(lineContent).forEach((value, key) => {
      lineObject[key] = value
    })
    return {
      ...lineObject,
      time: lineTime,
      date: lineTime.split(" ")[0],
      type: types.find(type => line.includes(type))
    }
  }
  return (
    <>
      <div className='page-wrap role-page-wrap'>
        <div className="scroll-ele-wrapper">
          <Card bordered={false}>
            <Space>
              <Select className='w-64' value={selectDate} onChange={onDateChange}>
                {data.dateList.map(e => <Select.Option key={e} value={e}>{e}</Select.Option>)}
              </Select>
              <RoleScreenshotDialog selectDate={selectDate}>
                <Button type='primary'>图片</Button>
              </RoleScreenshotDialog>
              
            </Space>
            <div className="mt-4">
              <Space>
                <Button type='primary' onClick={onHandleAutoXnTask}>交心能任务</Button>
                <Button type='primary' onClick={onHandleAuto_HLT_FACT_Quest}>交荒猎团任务</Button>
              </Space>
            </div>
          </Card>
          {subStat && (
            <Card bordered={false}>
              <Alert message={<><p dangerouslySetInnerHTML={{__html: subStat}}></p></>} type='success'></Alert>
            </Card>
          )}
          <Card bordered={false}>
            <Table
              scroll={{ x: 'max-content' }}
              rowKey={"role"}
              pagination={false}
              columns={columns}
              dataSource={tableDataSource}
              bordered
              size="middle"
            />
          </Card>
        </div>
      </div>
    </>
  )
}